<?php

namespace ApiWF\Controller;

use Common\Controller\ApibaseController;
use Think\Model;

/**
 * 金币商城
 */
class MallController extends ApibaseController
{

    /**
     * 金币商城首页
     */
    public function index()
    {
        $where = [
            'goods_status' => 1,
            '_string'=>'`goods_reper` > `sales_num`',
        ];

        $order = 'update_time desc';
        $goods = $this->pageHelper(D('CoinGoods'), $where,$order);
        foreach ($goods['list'] as $key => $value) {
            $goods['list'][$key]['good_coverage_image'] = qiniu_mirror_image_url_coin_good($value);
            htmlStringToPlainStirngArray($goods['list'][$key],'goods_description');
        }

        $banners = D('Slide')->where(['slide_cid' => 2, 'slide_status' => 1])->field('slide_id,slide_pic,slide_url')->order('listorder desc')->limit(6)->select();
        foreach ($banners as $key => $ban) {
            $banners[$key]['slide_pic'] = qiniu_mirror_image_url($ban['slide_pic']);
            $url = $ban['slide_url'];
            $banners[$key]['parameter_id'] = h5_url_parameter_id($url);
            $banners[$key]['h5_type'] = h5_url_type($url);
        }

        $this->jsonReturn(compact('goods', 'banners'), 'goods_type产品类型,1-普通产品，2-积分产品，3-金币产品,good_coin 消耗金币');
    }

    /**
     * 抽奖页面
     */
    public function lottery()
    {
        $uid = $this->parseTokenUID();

        $userInfo = D('Users')->where(['id' => $uid])->field(['coin' => 'my_gold_count'])->find();
        //抽奖信息
        $lottery = D('Lottery')->find();

        $start_time = strtotime($lottery['start_time']);
        $end_time = strtotime($lottery['end_time']);
        if($start_time < time() and time() < $end_time){
            $lottery['is_open'] = 1;
        }else {
            $lottery['is_open'] = 0;
            $lottery['lottery_description'] = '抽奖活动已经结束';
        }

        $data = compact('userInfo', 'lottery');
        $this->jsonReturn($data);
    }

    /**
     * 抽奖纪录分页  废弃
     */
    public function lotteryPrizeRecord(){
        $model =  D('LotteryLogView');
        $order = 'LotteryLog.create_time desc';
        //7是奖项设置的id 奖项表只能够修改不能增加删除
        $where = ['LotteryLog.goods_id'=>['NEQ',7]];
        $data = $this->pageHelper($model,$where,$order);
        $lottery_records = $data['list'];
        foreach ($lottery_records as $key=>$vo){
            $lottery_records[$key]['mobile'] = substr_replace($vo['mobile'],'****',3,4);
            $reward_coin = $vo['reward_coin'];
            if(intval($reward_coin)>0){
                $lottery_records[$key]['goods_intro'] = "奖励{$reward_coin}金币";
            }
        }
        $data['list'] = $lottery_records;
        $this->jsonReturn($data);
    }

    /**
     * 商品兑换
     */
    public function exchangeGood()
    {
        $uid = $this->parseTokenUID();
        $good_id = I('good_id', 1);
        $buying_count = I('buying_count', 1);

        $goodItem = D('CoinGoods')->where(['goods_status'=>['GT',0],'id'=>$good_id])->field('id')->find();
        if (empty($goodItem)) {
            $this->error('商品不存在!');
        }

        //获取商品信息 验证商品信息;
        $good_sql = "SELECT * FROM wf_coin_goods WHERE `goods_reper` > `sales_num` AND `id` = '$good_id' AND `goods_status` > 0";
        $goodItem = D('CoinGoods')->query($good_sql);
        if (empty($goodItem)) {
            $this->error('商品已经售罄!');
        }

        //获取商品金币单价
        $goods_price = $goodItem[0]['goods_price'];

        //判断用户余额
        $total_cost_coin = $buying_count * $goods_price;
        $user = D('Users')->where(['id' => $uid, 'coin' => ['GT', $total_cost_coin]])->field('coin')->find();
        if (empty($user)) {
            $this->error('用户金币余额不足');
        }

        //开始事物
        $M = new Model();
        $M->startTrans();

        //创建交易记录
        $data['uid'] = $uid;
        $data['goods_id'] = $good_id;
        $data['sale_count'] = $buying_count;
        $data['create_time'] = date('Y-m-d H:i:s');
        $data['update_time'] = date('Y-m-d H:i:s');
        //普通商品才有兑换码
        $goods_type = $goodItem[0]['goods_type'];
        $is_normal_good = $goods_type == '1';
        $data['convert_code'] = $is_normal_good ? (($uid%10000).date('-di-Hs')):'';

        $res0 = $M->table('wf_coin_goods_record')->add($data);
        if (!$res0) {
            $M->rollback();
            $this->error($M->getError());
        }

        //创建用户消费记录表
        //1:金币抽奖 2:金币奖品 3:积分兑换 4:新手任务 5:每日签到 6:金币兑换
        $description = "兑换商品数量{$buying_count},单价为{$goods_price}";
        $res1 = $this->addCoinRecord($uid,6, '兑换商品', $description, -$total_cost_coin);
        if (!$res1) {
            $M->rollback();
            $this->error($M->getError());
        }

        //修改库存
        $res2 = $M->table('wf_coin_goods')->where(['id' => $good_id])->setInc('sales_num');
        if (!$res2) {
            $M->rollback();
            $this->error($M->getError());
        }
        //TODO:积分兑金币 金币兑积分

        $M->commit();
        $info = D('CoinGoods')->field('sales_num')->where(['id'=>$good_id])->find();

        //获取用户金币数量
        $userCoin = D('Users')->field('coin')->where(['id'=>$uid])->find();

        $info['user_coin'] = $userCoin['coin'];
        $this->jsonReturn($info);

    }

    /**
     * 赚取金币说明
     */
    public function getGoldRule()
    {
        $data['title'] = '如何赚取积分？';
        $data['body'] = '被选为精华评论 +30分\r\n如果您对产品的评价被小编评选为精华评论后（次月公布），就能获得30分积分。\r\n会员生日积分 +30分\r\n会员生日当天，系统自动获赠30分积分。
微博晒盒子 抽奖购买礼盒后，在微博上分享礼盒，并且@我们的官方微博。我们会不定期的举办抽奖活动，免费';
        $this->jsonReturn($data);
    }

    /**
     * 幸运轮盘
     */
    public function fortuneWheel()
    {
        $where = 'UNIX_TIMESTAMP() > UNIX_TIMESTAMP(start_time) AND UNIX_TIMESTAMP() < UNIX_TIMESTAMP(end_time)';
        $lottery = D('Lottery')->where($where)->field('id,cost_gold')->find();
        if (empty($lottery)) {
            $this->error('抽奖活动未开始或者已经结束');
        }
        //判断用户余额
        $lottery_cost_gold = $lottery['cost_gold'];
        $uid = $this->parseTokenUID();
        $where = ['id' => $uid, 'coin' => ['GT', $lottery_cost_gold]];
        $userResult = D('Users')->where($where)->find();
        if (empty($userResult)) {
            $this->error('用户金币不够');
        }

        //开始事物
        $M = M();
        $M->startTrans();

        //扣除金币 支付
        $user_coin = $userResult['coin'];
        $remian_coin = $user_coin - $lottery_cost_gold;
        $payResult = D('Users')->where(['id' => $uid])->save(['coin' => $remian_coin]);
        if (!$payResult) {
            $M->rollback();
            $this->error('支付失败');
        }

        //中奖算法
        $lottery_goods = D('LotteryGoods')->where(['award_status' => 1])->field('`lottery_count` - `get_count` AS `remain_count`,`id`,`goods_avatar`,`goods_name`,`goods_description`,`reward_coin`,`get_count`')->order('reward_coin desc')->limit(5)->select();
        if (empty($lottery_goods)) {
            $M->rollback();
            $this->error('幸运轮盘没有奖品');
        }
        //彩票的总个数
        $lottery_arr = array_column($lottery_goods, 'remain_count');
        $pro_sum = array_sum($lottery_arr);
        // 概率数组循环
        $result = '';
        foreach ($lottery_arr as $key => $pro_cur) {
            $rand_num = mt_rand(1, $pro_sum);
            if ($rand_num <= $pro_cur) {
                $result = $key;
                break;
            } else {
                $pro_sum -= $pro_cur;
            }
        }
        $pick_lottery = $lottery_goods[$result];

        //修改库存
        $pick_lottery_id = $pick_lottery['id'];
        $res3 = D('LotteryGoods')->where(['id' => $pick_lottery_id])->setInc('get_count');
        if (!$res3) {
            $M->rollback();
            $this->error('修改奖品获取数量失败');
        }

        //创建中奖纪录
        $saveData = [
            'uid' => $uid,
            'goods_id' => $pick_lottery_id,
            'create_time' => date('Y-m-d H:i:s'),
        ];
        $res4 = D('LotteryLog')->add($saveData);
        if (!$res4) {
            $M->rollback();
            $this->error('纪录获奖纪录失败');
        }

        //创建用户消费
        //1:金币抽奖 2:金币奖品 3:积分兑换 4:新手任务 5:每日签到 6:金币兑换
        $res5 = $this->addCoinRecord($uid,1, '抽奖消费', "抽奖消费:{$lottery_cost_gold}", -$lottery_cost_gold);
        if (!$res5) {
            $M->rollback();
            $this->error('写入用户金币纪录失败');
        }
        //写入奖励金币数量
        $reward_coin = $pick_lottery['reward_coin'];
        //1:金币抽奖 2:金币奖品 3:积分兑换 4:新手任务 5:每日签到 6:金币兑换
        $res6 = $this->addCoinRecord($uid, 2, '中奖获取', "中奖获取:{$reward_coin}", $reward_coin);
        if (!$res6) {
            $M->rollback();
            $this->error('写入中奖金币纪录失败');
        }

        $M->commit();

        $lottery_data = D('LotteryGoods')->where(['id' => $pick_lottery_id])->find();
        $lottery_data['goods_avatar'] = qiniu_mirror_image_url_lottery($lottery_data);
        htmlStringToPlainStirngArray($lottery_data,'goods_description');
        //数据库降序和UI进行映射index
        $award_level = $lottery_data['award_level'];


        if($award_level == 1){
            $lottery_data['pointer_index'] = "1";
        }
        else if($award_level == 2){
            $lottery_data['pointer_index'] = "4";
        }
        else if($award_level == 3){
            $lottery_data['pointer_index'] = "2";
        }
        else if($award_level == 4){
            $lottery_data['pointer_index'] = "6";
        }else {
            //$award_level == 0
            //未中奖及其他
            $lottery_data['pointer_index'] = ['3','5'][rand(0,1)];
        }
        $this->jsonReturn($lottery_data);

    }

    /**
     * 获取金币兑换记录
     */
    public function userCoinExchangeRecord()
    {
        $uid = $this->parseTokenUID();
        $data = D('CoinGoodsRecordView')->where(compact('uid'))->order('update_time desc')->select();
        foreach ($data as $key => $vo) {
            $data[$key]['goods_pics'] = qiniu_mirror_image_url_coin_good($vo);
        }
        $this->jsonReturn($data);
    }

    public function userCoinExchangeRecordPagination()
    {
        $uid = $this->parseTokenUID();
        $model = D('CoinGoodsRecordView');
        $where = compact('uid');
        $order = 'update_time desc';
        $page_data = $this->pageHelper($model,$where,$order);
        $data = $page_data['list'];
        foreach ($data as $key => $vo) {
            $data[$key]['goods_pics'] = qiniu_mirror_image_url_coin_good($vo);
        }
        $page_data['list'] = $data;
        $this->jsonReturn($page_data);
    }


}